#pragma once

#include "log.hpp"
#include <iostream>
#include <cstdint>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <ctime>
#include <functional>

extern Log lg;

enum
{
    SOCKET_ERR = 1,
    BIND_ERR
};

using CallBack = std::function<std::string(const std::string &)>; 

class updserver
{
public:
    updserver(uint16_t port) : port_(port) {}

public:
    void Init()
    {
        //创建套接字
        fd_ = socket(AF_INET,SOCK_DGRAM,0);
        if(fd_ < 0){
            lg(Fatal,"socket create failed,fd: %d",fd_);
            exit(SOCKET_ERR);
        }

        //bind
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port_);
        local.sin_addr.s_addr = INADDR_ANY;
        socklen_t len = sizeof(local);
        int ret = bind(fd_,(struct sockaddr*)&local,len);
        if(ret < 0){
            lg(Fatal,"server bind failed, err string: %s",strerror(errno));
            exit(BIND_ERR);
        }

    }

    void Start(const CallBack &cb) 
    {
        while(true){
            char buf[1024] = {0};
            struct sockaddr_in client;
            socklen_t len = sizeof(client);

             //udp中 redvfrom返回值为0的情况代表对方发送了一个空的数据包，而在tcp中recv返回值为0的情况代表对方关闭了链接
            int n = recvfrom(fd_, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                 //出错了
                lg(Error,"server recvfrom error");
                continue;
            }
            buf[n] = 0;

            //获取客户端的IP和端口号
            std::string clientip = inet_ntoa(client.sin_addr);
            uint16_t clientport = ntohs(client.sin_port);

            lg(Info,"server recv a message: %s , client_ip: %s, client_port: %d",buf,clientip.c_str(),clientport);
            
            const std::string &echo_string = cb(buf);

            //发送响应报文
            n = sendto(fd_,echo_string.c_str(),echo_string.size(),0,(struct sockaddr*)&client,len);
            if(n < 0){
                lg(Error,"server sendto error");
                continue;
            }
        }
    }

private:
    int fd_;
    uint16_t port_;

};